<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '帖子详情',
    navigationBarBackgroundColor: '#f8f8f8',
    navigationBarTextStyle: 'black'
  },
}
</route>

<template>
  <view class="post-detail-container">
    <!-- 帖子内容 -->
    <view v-if="postDetail" class="post-content">
      <!-- 用户信息 -->
      <view class="post-header">
        <view class="user-info">
          <image class="user-avatar" :src="postDetail.userAvatar || '/static/images/default-avatar.png'" mode="aspectFill" />
          <view class="user-details">
            <text class="user-nickname">{{ postDetail.userNickname }}</text>
            <text class="post-time">{{ formatTime(postDetail.createTime) }}</text>
          </view>
        </view>
        <view class="post-header-actions">
          <view class="post-type-badge" v-if="postDetail.type === 'work'">
            <text class="badge-text">{{ postDetail.workType === 'book' ? '绘本' : '绘本集' }}</text>
          </view>
          <view
            v-if="postDetail.userId === Number(userStore.userInfo?.id)"
            class="delete-post-btn"
            @click="deletePostHandler"
          >
            <uni-icons type="trash" size="18" color="#999"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 作品信息（仅作品帖显示） -->
      <view v-if="postDetail.type === 'work' && postDetail.workCover" class="work-info" @click="goToWorkDetail">
        <image class="work-cover" :src="postDetail.workCover" mode="aspectFill" />
        <view class="work-details">
          <text class="work-title">{{ postDetail.workTitle }}</text>
          <text class="work-type">{{ postDetail.workType === 'book' ? '绘本作品' : '绘本集' }}</text>
        </view>
        <view class="work-arrow">
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 帖子正文 -->
      <view class="post-text-content">
        <text class="post-text">{{ postDetail.content }}</text>
      </view>

      <!-- 图片展示 -->
      <view v-if="postDetail.images && postDetail.images.length > 0" class="post-images">
        <view 
          v-for="(image, index) in postDetail.images" 
          :key="index" 
          class="image-item"
          :class="getImageClass(postDetail.images.length)"
          @click="previewImages(postDetail.images, index)"
        >
          <image :src="image" mode="aspectFill" />
        </view>
      </view>

      <!-- 互动区域 -->
      <view class="post-actions">
        <view class="action-item" @click="toggleLike">
          <uni-icons 
            :type="postDetail.isLiked ? 'heart-filled' : 'heart'" 
            :color="postDetail.isLiked ? '#ff4757' : '#999'" 
            size="20"
          ></uni-icons>
          <text class="action-text" :class="{ 'liked': postDetail.isLiked }">{{ postDetail.likeCount || '点赞' }}</text>
        </view>
        <view class="action-item">
          <uni-icons type="chat" color="#999" size="20"></uni-icons>
          <text class="action-text">{{ postDetail.commentCount || '评论' }}</text>
        </view>
        <!-- <view class="action-item">
          <uni-icons type="redo" color="#999" size="20"></uni-icons>
          <text class="action-text">分享</text>
        </view> -->
      </view>
    </view>

    <!-- 评论区域 -->
    <view class="comments-section">
      <view class="comments-header">
        <text class="comments-title">评论 {{ postDetail?.commentCount || 0 }}</text>
      </view>



      <!-- 空状态显示 -->
      <view v-if="commentList.length === 0 && !commentLoading" class="comments-empty-state">
        <view class="empty-icon">
          <uni-icons type="chat" size="48" color="#87ceeb"></uni-icons>
        </view>
        <text class="empty-title">暂无评论</text>
        <text class="empty-subtitle">快来发表第一条评论吧！</text>
      </view>

      <!-- 评论列表 -->
      <view v-else-if="commentList.length > 0" class="comments-list">
        <view v-for="(comment, index) in commentList" :key="comment.id" class="comment-item">
          <image class="comment-avatar" :src="comment.userAvatar || '/static/images/default-avatar.png'" mode="aspectFill" />
          <view class="comment-content">
            <view class="comment-header">
              <text class="comment-floor">#{{ index + 1 }}楼</text>
              <text class="comment-nickname">{{ comment.userNickname }}</text>
              <text class="comment-time">{{ formatTime(comment.createTime) }}</text>
            </view>
            <text class="comment-text">{{ comment.content }}</text>
            <view class="comment-actions">
              <view class="comment-action" @click="toggleCommentLike(comment)">
                <uni-icons
                  :type="comment.isLiked ? 'heart-filled' : 'heart'"
                  :color="comment.isLiked ? '#ff4757' : '#999'"
                  size="14"
                ></uni-icons>
                <text class="action-count">{{ comment.likeCount || '' }}</text>
              </view>
              <view class="comment-action" @click="replyToComment(comment)">
                <uni-icons type="redo" color="#999" size="14"></uni-icons>
                <text class="action-text">回复</text>
              </view>
              <view v-if="comment.userId === Number(userStore.userInfo?.id)" class="comment-action" @click="deleteComment(comment.id)">
                <uni-icons type="trash" color="#999" size="14"></uni-icons>
                <text class="action-text">删除</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-else-if="commentLoading" class="comments-loading">
        <uni-icons type="spinner-cycle" size="24" color="#87ceeb"></uni-icons>
        <text class="loading-text">加载中...</text>
      </view>
    </view>

    <!-- 底部评论输入框 -->
    <view class="comment-input-section">
      <!-- 回复状态提示 -->
      <view v-if="replyingTo" class="reply-status">
        <text class="reply-text">回复 @{{ replyingTo.nickname }}</text>
        <view class="reply-cancel" @click="clearReply">
          <uni-icons type="close" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <view class="comment-input-wrapper">
        <input
          ref="commentInputRef"
          v-model="commentContent"
          class="comment-input"
          type="text"
          placeholder="写评论..."
          :maxlength="300"
          @confirm="submitComment"
        />
        <button
          class="comment-submit-btn"
          :class="{ 'disabled': !commentContent.trim() }"
          :disabled="!commentContent.trim()"
          @click="submitComment"
        >
          发送
        </button>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-icons type="spinner-cycle" size="24" color="#007AFF"></uni-icons>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import {
  getPostDetail,
  getPostComments,
  togglePostLike,
  toggleCommentLike as toggleCommentLikeApi,
  createComment,
  deleteComment as deleteCommentApi,
  deletePost,
  checkSensitiveWords,
  type PostRespVO,
  type CommentRespVO
} from '@/api/community'
import { useUserStore } from '@/store/user'
import { formatRelativeTime } from '@/utils/time'

// 用户store
const userStore = useUserStore()

// 页面参数
const postId = ref<number>(0)

// 数据状态
const postDetail = ref<PostRespVO | null>(null)
const commentList = ref<CommentRespVO[]>([])
const commentContent = ref('')
const loading = ref(false)
const commentLoading = ref(true)

// 回复相关状态
const replyingTo = ref<{ nickname: string; userId: number } | null>(null)
const commentInputRef = ref<any>(null)



// 格式化时间
function formatTime(timeStr: string) {
  return formatRelativeTime(timeStr)
}

// 获取图片样式类
function getImageClass(imageCount: number) {
  if (imageCount === 1) return 'single-image'
  if (imageCount === 2) return 'double-image'
  return 'multiple-image'
}

// 预览图片
function previewImages(images: string[], current: number) {
  uni.previewImage({
    urls: images,
    current: current
  })
}

// 加载帖子详情
async function loadPostDetail() {
  console.log('📄 开始加载帖子详情:', postId.value)
  try {
    loading.value = true
    const response = await getPostDetail(postId.value)
    console.log('📥 帖子详情API响应:', response)

    if (response.code === 0 && response.data) {
      postDetail.value = response.data
      console.log('✅ 帖子详情加载成功:', {
        title: response.data.title,
        commentCount: response.data.commentCount,
        likeCount: response.data.likeCount
      })

      // 帖子详情加载完成后，触发评论列表加载
      loadComments()
      console.log('🔄 触发评论列表加载')
    } else {
      throw new Error(response.msg || '加载失败')
    }
  } catch (error) {
    console.error('💥 加载帖子详情失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    console.log('🏁 帖子详情加载完成')
  }
}

// 加载评论列表
async function loadComments() {
  console.log('🔄 开始加载评论列表:', { postId: postId.value })
  try {
    commentLoading.value = true
    const response = await getPostComments(postId.value, { pageNo: 1, pageSize: 50 })
    console.log('📥 评论API响应:', response)

    if (response.code === 0 && response.data) {
      const comments = response.data.list || []
      console.log('✅ 评论加载成功:', {
        total: response.data.total,
        listLength: comments.length,
        comments: comments
      })

      commentList.value = comments
      return comments
    } else {
      console.warn('❌ 获取评论失败:', response.msg)
      commentList.value = []
      return []
    }
  } catch (error) {
    console.error('💥 加载评论失败:', error)
    commentList.value = []
    return []
  } finally {
    commentLoading.value = false
    console.log('🏁 评论加载完成')
  }
}

// 切换帖子点赞
async function toggleLike() {
  if (!postDetail.value) return

  try {
    const response = await togglePostLike(postDetail.value.id)
    if (response.code === 0 && response.data) {
      postDetail.value.isLiked = response.data.isLiked
      postDetail.value.likeCount = response.data.likeCount
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

// 切换评论点赞
async function toggleCommentLike(comment: CommentRespVO) {
  try {
    const response = await toggleCommentLikeApi(comment.id)
    if (response.code === 0 && response.data) {
      comment.isLiked = response.data.isLiked
      comment.likeCount = response.data.likeCount
    }
  } catch (error) {
    console.error('评论点赞失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

// 回复评论
function replyToComment(comment: CommentRespVO) {
  replyingTo.value = {
    nickname: comment.userNickname,
    userId: comment.userId
  }
  commentContent.value = `@${comment.userNickname} `

  // 让输入框获得焦点
  nextTick(() => {
    if (commentInputRef.value) {
      commentInputRef.value.focus()
    }
  })
}

// 清除回复状态
function clearReply() {
  replyingTo.value = null
  if (commentContent.value.startsWith('@')) {
    const spaceIndex = commentContent.value.indexOf(' ')
    if (spaceIndex !== -1) {
      commentContent.value = commentContent.value.substring(spaceIndex + 1)
    } else {
      commentContent.value = ''
    }
  }
}

// 提交评论
async function submitComment() {
  if (!commentContent.value.trim()) return

  console.log('📝 开始提交评论:', {
    postId: postId.value,
    content: commentContent.value.trim(),
    currentCommentCount: postDetail.value?.commentCount,
    replyingTo: replyingTo.value
  })

  try {
    // 敏感词检测
    const sensitiveResponse = await checkSensitiveWords(commentContent.value.trim())
    console.log('🔍 敏感词检测结果:', sensitiveResponse)

    if (sensitiveResponse.code === 0 && sensitiveResponse.data) {
      const sensitiveData = sensitiveResponse.data as any
      if (sensitiveData.hasSensitive) {
        uni.showToast({
          title: `评论包含敏感词：${sensitiveData.sensitiveWords.join('、')}`,
          icon: 'none',
          duration: 3000
        })
        return
      }
    }

    const response = await createComment({
      postId: postId.value,
      content: commentContent.value.trim()
    })

    console.log('📤 评论提交API响应:', response)

    if (response.code === 0) {
      commentContent.value = ''
      replyingTo.value = null // 清除回复状态

      console.log('✅ 评论提交成功，开始刷新列表')

      uni.showToast({
        title: '评论成功',
        icon: 'success'
      })

      // 刷新评论列表
      console.log('🔄 重新加载评论列表')
      await loadComments()
      console.log('✅ 评论列表刷新完成')

      // 更新帖子评论数
      if (postDetail.value) {
        const oldCount = postDetail.value.commentCount
        postDetail.value.commentCount += 1
        console.log('📊 更新评论数:', {
          oldCount,
          newCount: postDetail.value.commentCount
        })
      }

      console.log('🎉 评论提交流程完成')
    } else {
      throw new Error(response.msg || '评论失败')
    }
  } catch (error) {
    console.error('💥 提交评论失败:', error)
    uni.showToast({
      title: error instanceof Error ? error.message : '评论失败',
      icon: 'none'
    })
  }
}

// 删除帖子
async function deletePostHandler() {
  if (!postDetail.value) return

  uni.showModal({
    title: '确认删除',
    content: '确定要删除这篇帖子吗？删除后无法恢复。',
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await deletePost(postDetail.value!.id)
          if (response.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })

            // 返回上一页
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          } else {
            throw new Error(response.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除帖子失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 删除评论
async function deleteComment(commentId: number) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条评论吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await deleteCommentApi(commentId)
          if (response.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })

            // 刷新评论列表
            loadComments()

            // 更新帖子评论数
            if (postDetail.value) {
              postDetail.value.commentCount -= 1
            }
          } else {
            throw new Error(response.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除评论失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 跳转到作品详情
function goToWorkDetail() {
  if (!postDetail.value || postDetail.value.type !== 'work') return
  
  uni.navigateTo({
    url: `/pages-sub/community/work-detail/index?workId=${postDetail.value.workId}&workType=${postDetail.value.workType}`
  })
}

// 监听评论列表变化
watch(commentList, (newList, oldList) => {
  console.log('📝 评论列表发生变化:', {
    oldLength: oldList?.length || 0,
    newLength: newList?.length || 0,
    newList: newList
  })
}, { deep: true })

onLoad((options: any) => {
  console.log('📱 页面加载:', options)
  if (options.id) {
    postId.value = parseInt(options.id)
    console.log('🆔 设置帖子ID:', postId.value)
    loadPostDetail()
  }
})
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.post-detail-container {
  min-height: 100vh;
  background: $bg-gradient;
  padding: $container-padding;
  padding-bottom: 80px; // 为底部评论输入框留空间
}

.post-content {
  background: $white;
  margin-bottom: 15px;
  padding: 20px;
  border-radius: $border-radius-xl;
  box-shadow: $shadow-sm;
}

.post-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;

  .user-info {
    display: flex;
    align-items: center;
    gap: 12px;

    .user-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }

    .user-details {
      display: flex;
      flex-direction: column;
      gap: 4px;

      .user-nickname {
        font-size: 16px;
        font-weight: 600;
        color: $dark-gray;
      }

      .post-time {
        font-size: 12px;
        color: $medium-gray;
      }
    }
  }

  .post-header-actions {
    display: flex;
    align-items: center;
    gap: 8px;

    .post-type-badge {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      padding: 4px 8px;
      border-radius: 10px;

      .badge-text {
        color: $white;
        font-size: 10px;
        font-weight: 600;
      }
    }

    .delete-post-btn {
      padding: 6px;
      border-radius: 50%;
      background: rgba($medium-gray, 0.1);
      transition: all 0.3s ease;

      &:active {
        background: rgba($medium-gray, 0.2);
        transform: scale(0.95);
      }
    }
  }
}

.work-info {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding: 12px;
  background: $gray-100;
  border-radius: $border-radius-lg;
  gap: 12px;

  .work-cover {
    width: 50px;
    height: 50px;
    border-radius: $border-radius-sm;
  }

  .work-details {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 4px;

    .work-title {
      font-size: 14px;
      font-weight: 600;
      color: $dark-gray;
    }

    .work-type {
      font-size: 12px;
      color: $medium-gray;
    }
  }
}

.post-text-content {
  margin-bottom: 15px;

  .post-text {
    font-size: 16px;
    line-height: 1.6;
    color: $dark-gray;
  }
}

.post-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;

  .image-item {
    border-radius: $border-radius-sm;
    overflow: hidden;

    &.single-image {
      width: 100%;
      height: 200px;
    }

    &.double-image {
      width: calc(50% - 4px);
      height: 120px;
    }

    &.multiple-image {
      width: calc(33.33% - 6px);
      height: 100px;
    }

    image {
      width: 100%;
      height: 100%;
    }
  }
}

.post-actions {
  display: flex;
  align-items: center;
  gap: 30px;
  padding-top: 15px;
  border-top: 1px solid $gray-200;

  .action-item {
    display: flex;
    align-items: center;
    gap: 6px;

    .action-text {
      font-size: 14px;
      color: $medium-gray;

      &.liked {
        color: #ff4757;
      }
    }
  }
}

.comments-section {
  background: $white;
  padding: 20px;
  border-radius: $border-radius-xl;
  box-shadow: $shadow-sm;
}

.comments-header {
  margin-bottom: 15px;

  .comments-title {
    font-size: 16px;
    font-weight: 600;
    color: $dark-gray;
  }
}

.comments-empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;

  .empty-icon {
    margin-bottom: 16px;
    opacity: 0.8;
  }

  .empty-title {
    font-size: 18px;
    font-weight: 600;
    color: $dark-gray;
    margin-bottom: 8px;
  }

  .empty-subtitle {
    font-size: 15px;
    color: $medium-gray;
    line-height: 1.4;
  }
}



.comments-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;

  .loading-text {
    font-size: 14px;
    color: $medium-gray;
    margin-top: 8px;
  }
}

.comment-item {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;

  .comment-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    flex-shrink: 0;
  }

  .comment-content {
    flex: 1;

    .comment-header {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 6px;

      .comment-floor {
        font-size: 11px;
        color: $primary-blue;
        font-weight: 600;
        background: rgba($primary-blue, 0.1);
        padding: 2px 6px;
        border-radius: 8px;
      }

      .comment-nickname {
        font-size: 14px;
        font-weight: 600;
        color: $dark-gray;
      }

      .comment-time {
        font-size: 12px;
        color: $medium-gray;
      }
    }

    .comment-text {
      font-size: 14px;
      line-height: 1.5;
      color: $dark-gray;
      margin-bottom: 8px;
    }

    .comment-actions {
      display: flex;
      align-items: center;
      gap: 15px;

      .comment-action {
        display: flex;
        align-items: center;
        gap: 4px;

        .action-count, .action-text {
          font-size: 12px;
          color: $medium-gray;
        }
      }
    }
  }
}

.comment-input-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: $white;
  border-top: 1px solid $gray-200;
  padding: 15px 20px;
  padding-bottom: calc(15px + env(safe-area-inset-bottom));

  .reply-status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: rgba($primary-blue, 0.1);
    padding: 8px 12px;
    border-radius: 8px;
    margin-bottom: 10px;

    .reply-text {
      font-size: 13px;
      color: $primary-blue;
      font-weight: 500;
    }

    .reply-cancel {
      padding: 2px;
      border-radius: 50%;
      background: rgba($medium-gray, 0.1);
    }
  }

  .comment-input-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .comment-input {
    flex: 1;
    padding: 10px 15px;
    background: $gray-100;
    border: none;
    border-radius: 20px;
    font-size: 14px;

    &::placeholder {
      color: $gray-500;
    }
  }

  .comment-submit-btn {
    padding: 8px 20px;
    background: $primary-blue;
    border: none;
    border-radius: 20px;
    color: $white;
    font-size: 14px;
    font-weight: 600;

    &.disabled {
      background: $gray-300;
      color: $gray-500;
    }
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  gap: 10px;

  .loading-text {
    font-size: 14px;
    color: $medium-gray;
  }
}
</style>
